﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Liang.UI.Tools
{
    public static class FormHelper
    {
        /// <summary>
        /// 创建列
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="width"></param>
        /// <param name="visuble"></param>
        /// <returns></returns>
        public static DataGridViewTextBoxColumn createTextColumn(string name, string value, int width, bool visuble)
        {
            DataGridViewTextBoxColumn result = new DataGridViewTextBoxColumn();
            result.HeaderText = name;
            result.DataPropertyName = value;
            result.Name = value;
            result.Width = width;
            result.Visible = visuble;
            return result;
        }

        public static DataGridViewTextBoxColumn createTextColumn_Right(string name, string value, int width, bool visuble)
        {
            DataGridViewTextBoxColumn result = new DataGridViewTextBoxColumn();
            result.HeaderText = name;
            result.DataPropertyName = value;
            result.Name = value;
            result.Width = width;
            result.Visible = visuble;
            result.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            return result;
        }

        /// <summary>
        /// 创建Link列
        /// </summary>
        /// <param name="selName"></param>
        /// <param name="name"></param>
        /// <param name="TextForLink"></param>
        /// <returns></returns>
        public static DataGridViewLinkColumnEx createLinkColumn(string selName, string name, bool TextForLink,int width = 50)
        {
            DataGridViewLinkColumnEx link = new DataGridViewLinkColumnEx();
            // 设定列的名字
            link.Name = selName;
            link.Text = name;
            // 设置列标题
            link.HeaderText = name;
            link.UseColumnTextForLinkValue = TextForLink;
            link.Width = width;
            return link;
        }

        public static DataGridViewComboBoxColumn createComboColumn(string name, string title)
        {
            DataGridViewComboBoxColumn comboBox = new DataGridViewComboBoxColumn();
            //列名
            comboBox.Name = name;
            //列标题
            comboBox.HeaderText = title;
            return comboBox;
        }

        public static DataGridViewCheckBoxColumnEx createCheckBoxColumn()
        {
            DataGridViewCheckBoxColumnEx checkBox = new DataGridViewCheckBoxColumnEx();
            checkBox.Width = 20;
            return checkBox;
        }

        /// <summary>
        /// 导出ini文件 序列化字符串为Json格式
        /// </summary>
        /// <param name="fileUrl">文件路径</param>
        /// <param name="data">数据字符串</param>
        public static void ExportIni(string fileUrl, string data)
        {
            if (File.Exists(fileUrl))
            {
                File.Delete(fileUrl);
            }
            FileStream fsMyfile = new FileStream(fileUrl, FileMode.Append, FileAccess.Write);
            StreamWriter swMyfile = new StreamWriter(fsMyfile);
            swMyfile.WriteLine(data);
            swMyfile.Flush();
            swMyfile.Close();
            fsMyfile.Close();
        }

        /// <summary>
        /// 导出ini文件 序列化T为Json格式
        /// </summary>
        /// <typeparam name="T">模型类型</typeparam>
        /// <param name="fileUrl">文件路径</param>
        /// <param name="t">模型对象</param>
        public static void ExportIni<T>(string fileUrl, T t)
        {
            if (File.Exists(fileUrl))
            {
                File.Delete(fileUrl);
            }

            string data = Liang.Util.Json.JsonTool.JsonSerializer(t);
            FileStream fsMyfile = new FileStream(fileUrl, FileMode.Append, FileAccess.Write);
            StreamWriter swMyfile = new StreamWriter(fsMyfile);
            swMyfile.WriteLine(data);
            swMyfile.Flush();
            swMyfile.Close();
            fsMyfile.Close();
        }


        /// <summary>
        /// 导出ini文件 序列化List为Json格式
        /// </summary>
        /// <typeparam name="T">模型类型</typeparam>
        /// <param name="fileName"></param>
        /// <param name="tlist"></param>
        public static void ExportIni<T>(string fileUrl, List<T> tlist)
        {
            if (File.Exists(fileUrl))
            {
                File.Delete(fileUrl);
            }
            string data = Liang.Util.Json.JsonTool.JsonSerializer(tlist);
            FileStream fsMyfile = new FileStream(fileUrl, FileMode.Append, FileAccess.Write);
            StreamWriter swMyfile = new StreamWriter(fsMyfile);
            swMyfile.WriteLine(data);
            swMyfile.Flush();
            swMyfile.Close();
            fsMyfile.Close();
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="dataGridView"></param>
        public static void ExportExcel(string fileName, DataGridView dataGridView)
        {
            string saveFileName = "";
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = fileName;
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0)
                return;
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("创建Excel失败，可能未安装Excel");
                return;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
            int colIndex = 0;
            for (int i = 0; i < dataGridView.ColumnCount; i++)
            {
                if (dataGridView.Columns[i].Visible && !dataGridView.Columns[i].GetType().Equals(typeof(DataGridViewLinkColumnEx)))//排除隐藏列和链接列
                {
                    colIndex++;
                    worksheet.Cells[1, colIndex] = dataGridView.Columns[i].HeaderText;
                }
            }
            for (int r = 0; r < dataGridView.Rows.Count; r++)
            {
                colIndex = 0;
                for (int i = 0; i < dataGridView.ColumnCount; i++)
                {
                    if (dataGridView.Columns[i].Visible && !dataGridView.Columns[i].GetType().Equals(typeof(DataGridViewLinkColumnEx)))//排除隐藏列和链接列
                    {
                        colIndex++;
                        worksheet.Cells[r + 2, colIndex] = dataGridView.Rows[r].Cells[i].Value;
                    }
                }
                System.Windows.Forms.Application.DoEvents();
            }
            worksheet.Columns.EntireColumn.AutoFit();
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("导出文件出错。" + ex.Message);
                }
            }
            xlApp.Quit();
            GC.Collect();
            MessageBox.Show(fileName + ".xls 保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }


        public static void ExpListViewExcel(ListView listView, string fileName)
        {
            string saveFileName = "";
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = fileName;
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0)
                return;
            if (listView.Items.Count == 0) return;
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("创建Excel失败，可能未安装Excel");
                return;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
            xlApp.Cells[1, 4] = fileName;
            for (int x = 1; x <= listView.Columns.Count; x++)
            {

                xlApp.Rows.Cells[2, x] = listView.Columns[x - 1].Text;
            }
            for (int i = 3; i <= listView.Items.Count + 2; i++)
            {
                for (int j = 1; j <= listView.Columns.Count; j++)
                {
                    xlApp.Rows.Cells[i, j] = listView.Items[i - 3].SubItems[j - 1].Text;
                }
            }

            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("导出文件出错。" + ex.Message);
                }
            }
            xlApp.Quit();
            GC.Collect();
            MessageBox.Show(fileName + ".xls 保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 选择筛选后的文件
        /// </summary>
        /// <param name="strRootPath"></param>
        /// <returns></returns>
        public static string FileFilter(string strRootPath, string strFilter = "*")
        {
            FormSelectFile formSelectFile = new FormSelectFile(strRootPath, strFilter);

            if (DialogResult.OK == formSelectFile.ShowDialog())
            {
                return formSelectFile.SelectedFile;
            }

            return string.Empty;
        }
    }
}
